import "./index.scss";
import { useEffect, useState } from "react";
import {
  SearchOutlined,
  DoubleLeftOutlined,
  CloseOutlined,
} from "@ant-design/icons";
import {
  Divider,
  Button,
  Table,
  Form,
  Input,
  Drawer,
  Select,
  Modal,
  Breadcrumb,
  message,
} from "antd";
import type { ColumnsType } from "antd/es/table";
import type { DrawerProps, RadioChangeEvent } from "antd";
import { useNavigate } from "react-router-dom";
import {
  get,
  del,
  add,
  edit,
  getSenior,
} from "../../../apis/balance/balanceApi";
interface DataType {
  key: React.Key;
  name: string;
  balance: number;
  createdate: string;
  type: string;
}
const Balance: React.FC = () => {
  const [messageApi, contextHolder] = message.useMessage();
  const [search, setSearch] = useState([]);
  // 数据渲染
  const getBalance = (values: any) => {
    get(values).then((res: { [propName: string]: any }) => {
      if (res.error == 0) {
        let _data = res.data.map((v: { [propName: string]: any }) => {
          if (v.createdate) {
            let time1 = v.createdate.split("T");
            let time2 = time1[1].split(".000Z");
            let time = time1[0].concat("  ", time2[0]);
            v.createdate = time;
          }
          return { ...v };
        });
        setData(_data);
      } else if (res.error == 1) {
        messageApi.open({
          type: "error",
          content: "没有该用户",
          className: "custom-class",
          style: {},
        });
      }
    });
  };
  /* 一上来请求数据 */
  useEffect(() => {
    getBalance(search);
  }, []);

  //查询
  const onSearch = (search: { [propName: string]: any }) => {
    let searchData = { ...search };
    setSearch(searchData.username);
    getBalance(searchData.username);
  };
  // 重置
  const reload = () => {
    getBalance("");
  };

  //新增
  const [openAdd, setOpenAdd] = useState(false);
  const [placementAdd] = useState<DrawerProps["placement"]>("top");
  const onAdd = () => {
    setOpenAdd(true);
  };
  const onCloseAdd = () => {
    setOpenAdd(false);
  };
  const addData = (values: any) => {
    add(values).then((res: { [key: string]: any }) => {
      if (res.code == 200) {
        message.success("添加成功");
        setOpenAdd(false);
        getBalance(search);
      }
    });
  };

  /* 编辑 */
  const [editForm] = Form.useForm();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const showModal = (record: any) => {
    editForm.setFieldsValue({ ...nowData });
    setIsModalOpen(true);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  const onEdit = () => {
    const data = editForm.getFieldsValue(true);
    console.log("编辑数据", data);
    edit(data).then((res: { [propName: string]: any }) => {
      console.log(res);
      if (res.code == 200) {
        message.success("修改成功");
        setIsModalOpen(false);
        getBalance(search);
      }
    });
  };

  // 删除
  const [delModalOpen, setDelModalOpen] = useState(false);

  const delModal = () => {
    setDelModalOpen(true);
  };

  const delOk = () => {
    console.log("删除数据", nowData);
    del(nowData).then((res: { [propName: string]: any }) => {
      console.log(res);
      if (res.code == 200) {
        message.success("删除成功");
        setDelModalOpen(false);
        getBalance(search);
      }
    });
  };
  const delCancel = () => {
    setDelModalOpen(false);
  };

  //打开高级筛选
  const senior = () => {
    if (open == false) {
      setOpen(true);
    } else {
      setOpen(false);
    }
  };
  //高级筛选
  const [open, setOpen] = useState(false);
  const [placement, setPlacement] = useState<DrawerProps["placement"]>("top");
  const onClose = () => {
    setOpen(false);
  };
  const seniorSel = (values: any) => {
    getSenior(values).then((res: { [propName: string]: any }) => {
      if (res.code == 200) {
        let _data = res.data.map((v: { [propName: string]: any }) => {
          if (v.createdate) {
            let time1 = v.createdate.split("T");
            let time2 = time1[1].split(".000Z");
            let time = time1[0].concat("  ", time2[0]);
            v.createdate = time;
          }
          return { ...v };
        });
        setData(_data);
        message.success("筛选成功");
        setOpen(false);
      }
    });
  };
  const iStyle = {
    color: "#d6d6d6",
  };

  //当前数据
  const [nowData, setNowData] = useState({});

  //单选内容操作
  const rowSelection = {
    onChange: (
      selectedRowKeys: { [propName: string]: any },
      selectedRows: DataType[]
    ) => {
      console.log(`key值: ${selectedRowKeys}`, "数据: ", selectedRows[0]);
      setNowData({ ...selectedRows[0] });
    },
    getCheckboxProps: (record: DataType) => ({
      name: record.name,
      // disabled: record.key === "1",
    }),
  };

  //学校账户
  const navigate = useNavigate();
  const goAssociatedUsers = () => {
    navigate("/home/account/schoolAccount");
  };

  // 表头数据
  const columns: ColumnsType<DataType> = [
    {
      title: "用户名称",
      dataIndex: "username",
      render: (text: string) => <a>{text}</a>,
      align: "center",
    },
    {
      title: "账户余额",
      dataIndex: "balance",
      align: "center",
    },
    {
      title: "创建时间",
      dataIndex: "createdate",
      align: "center",
    },
    {
      title: "类型",
      dataIndex: "type",
      align: "center",
    },
    {
      title: "状态",
      dataIndex: "status",
      align: "center",
      render: (text: string) => <p>{text == "1" ? "正常" : "欠费"}</p>,
    },
    {
      title: "备注",
      dataIndex: "balmsg",
      align: "center",
      render: (text: string) => <p>{text != null ? text : "无备注"}</p>,
    },
  ];
  //表格数据
  const [data, setData] = useState([]);
  /* const data: DataType[] = [
    {
      key: "1",
      name: "John Brown",
      balance: 32,
      time: "2022-12-01",
      type: "系统管理员",
    },
    {
      key: "2",
      name: "Jim Green",
      balance: 42,
      time: "2022-12-01",
      type: "系统管理员",
    },
    {
      key: "3",
      name: "Joe Black",
      balance: 32,
      time: "2022-12-01",
      type: "系统管理员",
    },
    {
      key: "4",
      name: "Disabled User",
      balance: 99,
      time: "2022-12-01",
      type: "系统管理员",
    },
    {
      key: "5",
      name: "Disabled User",
      balance: 99,
      time: "2022-12-01",
      type: "系统管理员",
    },
    {
      key: "6",
      name: "Disabled User",
      balance: 99,
      time: "2022-12-01",
      type: "系统管理员",
    },
    {
      key: "7",
      name: "Disabled User",
      balance: 99,
      time: "2022-12-01",
      type: "系统管理员",
    },
  ]; */
  const pagination = {
    defaultPageSize: 5,
    defaultCurrent: 1,
    total: data.length,
    showQuickJumper: true,
    showSizeChanger: true,
    pageSizeOptions: [5, 10, 15, 20],
  };

  return (
    <div className="balance">
      {/* 路径 */}
      <div className="title">
        <Breadcrumb separator=">">
          <Breadcrumb.Item>余额管理</Breadcrumb.Item>
          <Breadcrumb.Item href="">余额管理</Breadcrumb.Item>
        </Breadcrumb>
      </div>
      <Divider />
      {/* 增删改查 */}
      <div>
        <Form className="search" layout="inline" onFinish={onSearch}>
          <Form.Item>
            <Button
              type="primary"
              style={{ background: "#69657e" }}
              onClick={onAdd}
            >
              新增
            </Button>
          </Form.Item>
          <Form.Item>
            <Button
              onClick={showModal}
              type="primary"
              style={{ background: "#69657e" }}
            >
              修改
            </Button>
          </Form.Item>
          <Form.Item>
            <Button
              onClick={delModal}
              type="primary"
              style={{ background: "#69657e" }}
            >
              删除
            </Button>
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              style={{ background: "#69657e" }}
              onClick={goAssociatedUsers}
            >
              学校账户
            </Button>
          </Form.Item>
          <Form.Item name="username">
            <Input placeholder="请输入用户姓名" />
          </Form.Item>
          <Form.Item>
            {contextHolder}
            <Button
              type="primary"
              style={{ background: "#69657e" }}
              icon={<SearchOutlined />}
              htmlType="submit"
            >
              搜索
            </Button>
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              style={{ background: "#69657e" }}
              onClick={reload}
            >
              重置
            </Button>
          </Form.Item>
          <Divider type="vertical" className="ver" />
          <Form.Item>
            <Button type="link" style={{ color: "#52a6ff" }} onClick={senior}>
              高级筛选
              <DoubleLeftOutlined rotate={270} style={iStyle} />
            </Button>
          </Form.Item>
        </Form>
      </div>
      {/* 高级筛选弹框 */}
      <div className="site-drawer-render-in-current-wrapper">
        <Drawer
          placement={placement}
          closable={false}
          onClose={onClose}
          open={open}
          key={placement}
          getContainer={false}
          height={150}
        >
          <Form className="senior" layout="inline" onFinish={seniorSel}>
            <Form.Item
              label="余额类型"
              name="type"
              rules={[
                {
                  required: true,
                  message: "请选择类型",
                },
              ]}
            >
              <Select style={{ width: 180 }} placeholder="请选择余额类型">
                <Select.Option value="充值">充值</Select.Option>
                <Select.Option value="缴费">缴费</Select.Option>
              </Select>
            </Form.Item>
            <Form.Item label="用户名称" name="username">
              <Input placeholder="请输入姓名" />
            </Form.Item>
            <Form.Item
              label="状态"
              name="status"
              rules={[
                {
                  required: true,
                  message: "请选择状态",
                },
              ]}
            >
              <Select style={{ width: 180 }} placeholder="请选择状态">
                <Select.Option value="1">正常</Select.Option>
                <Select.Option value="2">欠费</Select.Option>
              </Select>
            </Form.Item>
            <div
              className="seniorClose"
              onClick={() => {
                setOpen(false);
              }}
            >
              <CloseOutlined />
            </div>
            <div className="seniorBtn">
              <Form.Item>
                <Button
                  type="primary"
                  style={{ background: "#69657e" }}
                  htmlType="submit"
                >
                  查询
                </Button>
              </Form.Item>
              <Form.Item>
                <Button
                  type="primary"
                  style={{ background: "#69657e" }}
                  onClick={() => {
                    setOpen(false);
                  }}
                >
                  取消
                </Button>
              </Form.Item>
            </div>
          </Form>
        </Drawer>
      </div>

      {/* 表格 */}
      <Table
        rowSelection={{
          type: "radio",
          ...rowSelection,
        }}
        bordered={true}
        columns={columns}
        dataSource={data}
        pagination={pagination}
      />
      {/* 新增 { username, balance, type, status, balmsg }*/}
      <div className="add">
        <Drawer
          title="余额管理   新增"
          placement={placementAdd}
          closable={false}
          onClose={onCloseAdd}
          open={openAdd}
          key={placement}
          contentWrapperStyle={{
            position: "absolute",
            top: "25%",
            left: "20%",
            width: "60%",
          }}
        >
          <Form
            className="addForm"
            layout="inline"
            onFinish={addData}
            style={{ position: "relative", justifyContent: "center" }}
          >
            <Form.Item label="余额类型" name="type">
              <Select style={{ width: 180 }} placeholder="请选择">
                <Select.Option value="充值">充值</Select.Option>
                <Select.Option value="缴费">缴费</Select.Option>
              </Select>
            </Form.Item>
            <Form.Item
              label="金额"
              name="balance"
              style={{ margin: "0 10px 8px 8px" }}
            >
              <Input placeholder="请输入金额" />
            </Form.Item>
            <Form.Item
              label="用户名称"
              name="username"
              style={{ margin: "0 10px 8px 8px" }}
            >
              <Input placeholder="请输入角色名称" />
            </Form.Item>
            <Form.Item label="状态" name="status">
              <Select style={{ width: 100 }} placeholder="请选择">
                <Select.Option value="1">正常</Select.Option>
                <Select.Option value="2">欠费</Select.Option>
              </Select>
            </Form.Item>
            <Form.Item
              label="备注"
              name="balmsg"
              style={{ marginLeft: "10px", marginTop: "20px" }}
              rules={[
                {
                  required: true,
                  message: "记得备注哟~",
                },
              ]}
            >
              <Input.TextArea rows={5} cols={100} />
            </Form.Item>
            {/* <CloseOutlined /> */}
            <div
              className="addClose"
              onClick={() => {
                setOpen(false);
              }}
            ></div>
            <div className="addBtn">
              <Form.Item>
                <Button
                  type="primary"
                  style={{
                    background: "#69657e",
                    position: "absolute",
                    top: "160px",
                    left: "-480px",
                  }}
                  htmlType="submit"
                >
                  保存
                </Button>
                <Button
                  type="primary"
                  style={{
                    background: "#69657e",
                    position: "absolute",
                    top: "160px",
                    left: "-380px",
                  }}
                  onClick={() => {
                    onCloseAdd();
                  }}
                >
                  取消
                </Button>
              </Form.Item>
            </div>
          </Form>
        </Drawer>
      </div>
      {/* 编辑 */}
      <Modal
        title="编辑"
        open={isModalOpen}
        onOk={onEdit}
        onCancel={handleCancel}
      >
        <Form
          form={editForm}
          labelCol={{
            span: 6,
          }}
          wrapperCol={{
            span: 16,
          }}
          autoComplete="off"
        >
          <Form.Item label="编号" name="key">
            <Input disabled />
          </Form.Item>
          <Form.Item
            label="姓名"
            name="username"
            rules={[
              {
                required: true,
                message: "必须添加姓名",
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item label="类型" name="type">
            <Input disabled />
          </Form.Item>

          <Form.Item
            label="金额"
            name="balance"
            rules={[
              {
                required: true,
                message: "请输入金额",
              },
            ]}
          >
            <Input type="number" />
          </Form.Item>
          <Form.Item
            label="状态"
            name="status"
            rules={[
              {
                required: true,
                message: "请输入金额",
              },
            ]}
          >
            <Select placeholder="请选择">
              <Select.Option value={1}>正常</Select.Option>
              <Select.Option value={2}>欠费</Select.Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>

      {/* 删除 */}
      <Modal
        title="删除提示"
        open={delModalOpen}
        onOk={delOk}
        onCancel={delCancel}
      >
        <p>确定要删除？</p>
      </Modal>
    </div>
  );
};
export default Balance;
